﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Shapes;

using Aliphant.Mvvm.XEvent.Events;
using Aliphant.Mvvm.XEvent.UI;
using Aliphant.UI.Forms.Helpers;

namespace TsingStandardModule.ViewModels
{
    public class WidgetTSViewModel : BindableBase
    {
        private StringBuilder _sb = new StringBuilder();
        private Queue<string> _messageQueue = new Queue<string>();
        private CancellationTokenSource _cts = new CancellationTokenSource();
        private object _lock = new object();
        private WindowEvent _windowEvent;

        public WidgetTSViewModel()
        {
            _windowEvent = TSModule.EventAgent.GetEvent<WindowEvent>();
            _windowEvent.Subscribe(Release, (p) => p.Type == EventType.Action && p.WindowActionType == WindowActionType.Close && p.EventId == EventIds.Release);

            CalculationTypeCollection.Add("查找");

            FilterTypeCollection.Add("字符匹配");
            FilterTypeCollection.Add("正则表达式");

            Task.Factory.StartNew(() =>
            {
                while (!_cts.IsCancellationRequested)
                {
                    if (_messageQueue.Count <= 0)
                    {
                        continue;
                    }

                    lock (_lock)
                    {
                        string message = _messageQueue.Dequeue();
                        AddLog(message);
                    }
                }
            });
        }


        private string _filePath = string.Empty;
        public string FilePath { get => _filePath; set => SetProperty(ref _filePath, value); }

        private string _calculationType = string.Empty;
        public string CalculationType { get => _calculationType; set => SetProperty(ref _calculationType, value); }

        private string _filterKeys = string.Empty;
        public string FilterKeys { get => _filterKeys; set => SetProperty(ref _filterKeys, value); }

        private string _result = string.Empty;
        public string Result { get => _result; set => SetProperty(ref _result, value); }

        private string _filterType = string.Empty;
        public string FilterType { get => _filterType; set => SetProperty(ref _filterType, value); }

        public ObservableCollection<string> CalculationTypeCollection { get; private set; } = new();
        public ObservableCollection<string> FilterTypeCollection { get; private set; } = new();

        public ICommand SelectFilePathCommand
        {
            get => new UICommand<object>(obj =>
            {
                Action<string> callback = (r) =>
                {
                    FilePath = r;
                };
                MessageBox.Show("123");
                DialogHelper.SelectFolderWindow(new WindowEvent()
                {
                    Data = "所有文件(*.*)|*.*",
                    CallBack = callback
                });
            });
        }

        public ICommand RunCommand
        {
            get => new UICommand<object>(obj =>
            {
                _sb.Clear();
                Result = string.Empty;
                switch (CalculationType)
                {
                    case "查找":
                        FindKeys();
                        break;
                }
            });
        }


        private void AddLog(string message)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                _sb.AppendLine(message);
                Result = _sb.ToString();
            });
        }


        #region 查找

        private void FindKeys()
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                AddLog("文件为空");
                return;
            }
            if (string.IsNullOrEmpty(FilterKeys))
            {
                AddLog("筛选关键字为空");
                return;
            }
            string[] files = Directory.GetFiles(FilePath);
            if (files.Length <= 0)
            {
                AddLog("文件夹为空");
                return;
            }

            Action<int, string> action;

            if (FilterType == "正则表达式")
            {
                action = (index, line) =>
                {
                    Regex regex = new Regex(FilterKeys);
                    if (regex.IsMatch(line))
                    {
                        lock (_lock)
                        {
                            _messageQueue.Enqueue($"[Line: {index}]  {line}");
                        }
                    }
                };
            }
            else
            {
                action = (index, line) =>
                {
                    if (line.Contains(FilterKeys))
                    {
                        lock (_lock)
                        {
                            _messageQueue.Enqueue($"[Line: {index}]  {line}");
                        }
                    }
                };
            }

            Task.Factory.StartNew(() =>
            {
                foreach (var file in files)
                {
                    AddLog(file.Trim());
                    string[] lines = File.ReadLines(file).ToArray();
                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (string.IsNullOrEmpty(lines[i]))
                        {
                            continue;
                        }
                        action(i + 1, lines[i]);
                    }
                }
            });
        }

        #endregion


        private void Release(WindowEvent @event)
        {
            _cts.Cancel();
        }

    }
}
